package com.aliang.shopping.util;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.lang.Dict;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.List;

/**
 * 邮箱工具类
 */
@Component
public class MailUtil {

    private final JavaMailSenderImpl mailSender;
    private TemplateEngine engine;

    MailUtil(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }

    @Value("${spring.mail.username}")
    private String from;

    @PostConstruct
    public void init() {
        Session session = mailSender.getSession();
        session.getProperties().setProperty("mail.smtp.localhost", "shibalover.love");
        System.getProperties().setProperty("mail.mime.address.usecanonicalhostname", "false");
        // 创建模板引擎
        engine = TemplateUtil.createEngine(new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));
    }


    /**
     * 发送验证码
     */
    public void sendCode(String email, String code) {
        TimeInterval timer = DateUtil.timer();
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            //渲染邮件模版
            Template template = engine.getTemplate("mailtemplate.ftl");
            String content = template.render(Dict.create().set("code", code));
            //设置一个html邮件信息
            helper.setText(content, true);
            //设置邮件主题名
            helper.setSubject("云选购物系统-邮箱验证码");
            //发给谁-》邮箱地址
            helper.setTo(email);
            helper.setFrom("阿良<" + from + ">");
        } catch (MessagingException e) {
            throw new ServiceException(ResultCodeEnum.EMAIL_CODE_SEND_ERROR);
        }
        System.out.println("渲染花费的时间：" + timer.intervalRestart());
        // 发送信息
        mailSender.send(mimeMessage);
        System.out.println("发送花费的时间：" + timer.intervalRestart());
    }

    /**
     * 发送验证邮箱
     */
    public void sendValidateEmail(String email) {
        TimeInterval timer = DateUtil.timer();
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            //渲染邮件模版
            Template template = engine.getTemplate("message.ftl");
            String content = template.render(new HashMap<>());
            //设置一个html邮件信息
            helper.setText(content, true);
            //设置邮件主题名
            helper.setSubject("云选购物系统-验证邮箱");
            //发给谁-》邮箱地址
            helper.setTo(email);
            helper.setFrom("阿良<" + from + ">");
        } catch (MessagingException e) {
            throw new ServiceException(ResultCodeEnum.EMAIL_SEND_ERROR);
        }
        System.out.println("渲染花费的时间：" + timer.intervalRestart());
        // 发送信息
        mailSender.send(mimeMessage);
        System.out.println("发送花费的时间：" + timer.intervalRestart());
    }

    /**
     * 发送审核结果通知
     */
    public void sendValidateFailEmail(String email, String msg) {
        sendOneNoticeMail(new String[]{email}, msg, "云选购物系统-店铺资质审核结果通知");
    }

    private void sendOneNoticeMail(String[] email, String msg, String subject) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            //渲染邮件模版
            Template template = engine.getTemplate("validate_msg.ftl");
            String content = template.render(Dict.create().set("msg", msg));
            //设置一个html邮件信息
            helper.setText(content, true);
            //设置邮件主题名
            helper.setSubject(subject);
            //发给谁-》邮箱地址
            helper.setTo(email);
            helper.setFrom("阿良<" + from + ">");
        } catch (MessagingException e) {
            throw new ServiceException(ResultCodeEnum.EMAIL_CODE_SEND_ERROR);
        }
        // 发送信息
        mailSender.send(mimeMessage);
    }

    public void sendNoticeEmail(String email, String msg) {
        sendOneNoticeMail(new String[]{email}, msg, "云选购物系统-通知邮件");
    }

    public void sendNoticeBatchEmail(List<String> mails, String msg) {
        sendOneNoticeMail(mails.toArray(new String[0]),msg,"云选购物系统-通知邮件");
    }
}